/*
 * StatusApplication.java
 *
 * Created on April 22, 2007, 10:34 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.xeerkat.agent.apps;

import java.util.Date;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Status;
import org.restlet.representation.StringRepresentation;
import org.restlet.routing.Router;
import org.xeerkat.agent.AgentContext;
import org.xeerkat.agent.services.ServiceMetadata;
import org.xeerkat.agent.util.XSDDate;
import org.xeerkat.xmpp.ID;

/**
 *
 * @author alex
 */
@ServiceMetadata(id="http://www.xeerkat.org/Services/Status/2007/1/0/1",vendor="xeerkat.org",copyright="2008 xeerkat.org")
public class StatusApplication extends Application
{

   Date startTime;
   boolean available;
   AgentContext agentContext;
   
   /** Creates a new instance of StatusApplication */
   public StatusApplication(Context context)
   {
      this.startTime = new Date();
      this.available = true;
      agentContext = (AgentContext)context.getAttributes().get(AgentContext.AGENT_CONTEXT_ATTR);
   }
   
   public boolean isAvailable() {
      return available;
   }
   
   public void setAvailable(boolean flag)
   {
      available = flag;
   }
   
   public Restlet createRoot() {
      Router router = new Router();
      router.attach("/available", new Restlet() {
         public void handle(Request request,Response response)
         {
            if (request.getMethod().equals(Method.GET)) {
               response.setStatus(available ? Status.SUCCESS_NO_CONTENT : Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
            } else {
               response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
            }
         }
      });
      Restlet stat = new Restlet() {
         public void handle(Request request, Response response) {
            if (!request.getMethod().equals(Method.GET)) {
               response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
               return;
            }
            ID identity = agentContext.getIdentity();
            Date current = new Date();
            response.setStatus(Status.SUCCESS_OK);
            String version = AgentContext.class.getPackage().getImplementationVersion();
            response.setEntity(new StringRepresentation("<status id='"+identity+"' available='"+available+"' connected='"+agentContext.getAgentMonitor().isConnected()+"' up-since='"+XSDDate.toString(startTime)+"' uptime='"+(current.getTime()-startTime.getTime())+"' version='"+version+"'/>",MediaType.APPLICATION_XML));
         }
      };
      router.attach("/",stat);
      router.attach("",stat);
      return router;
   }
   
}
